package com.dqp.cslggroup;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.dateUtil;
import com.dqp.cslggroup.bean.avatar;
import com.dqp.cslggroup.bean.student;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.List;

public class personal_center extends BaseActivity {
    private ViewPager viewpager;
    private ImageView iv_parallax;
    private ImageView iv_back;
    private ImageView iv_date;
    private ImageView iv_head;
    private LinearLayout buttonBarLayout;
    private CollapsingToolbarLayout collapsing_toolbar;
    private AppBarLayout appbar;
    private Toolbar toolbar;
    boolean isblack = false;
    boolean iswhite = true;
    private TabLayout tabLayout;
    private TextView xm, zy, xy;
    private SharedPreferences sp;
    private Boolean isFirstIn;
    private byte[] in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center);
        EventBus.getDefault().register(this);
        initView();
        frist_per();
        initText();
        initListener();
        initViewPager();

    }

    @SuppressLint("HandlerLeak")
    public void frist_per() {
        sp = getSharedPreferences("first_open_per", MODE_PRIVATE);
        isFirstIn = sp.getBoolean("is_first_open_per", true);
    }


    @SuppressLint("HandlerLeak")
    private void initView() {
        appbar = findViewById(R.id.appbar);
        viewpager = findViewById(R.id.view_pager);
        iv_parallax = findViewById(R.id.iv_parallax);
        buttonBarLayout = findViewById(R.id.buttonBarLayout);
        collapsing_toolbar = findViewById(R.id.collapsing_toolbar);
        tabLayout = findViewById(R.id.tabs);
        toolbar = findViewById(R.id.toolbars);
        iv_back = findViewById(R.id.iv_back);
        iv_date = findViewById(R.id.iv_date);
        iv_head = findViewById(R.id.iv_head);
        xm = findViewById(R.id.nickname);
        xy = findViewById(R.id.xy);
        zy = findViewById(R.id.zy);
        mImmersionBar.titleBar(toolbar).init();
        iv_back.setOnClickListener(v -> personal_center.this.finish());
        iv_date.setOnClickListener(v -> {
            AlertDialog alertDialog = new AlertDialog(personal_center.this);
            alertDialog.builder();
            alertDialog.setGone()
                    .setTitle("注销")
                    .setMsg("注销后部分数据将会被清空！")
                    .setNegativeButton("注销", R.color.colorAccent, v1 -> new Thread(() -> {
                        try {
                            dateUtil.deletData(personal_center.this);
                            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }).start())
                    .setPositiveButton("取消", R.color.colorAccent, null)
                    .show();
        });
    }


    private void initText() {
        String nj;
        int njs;
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList != null && studentList.size() > 0) {
            student student = studentList.get(0);
            String xm_text = student.getXm();
            String xy_text = student.getXy();
            String zy_text = student.getZy();
            String xb_text = student.getXb();
            String syd_text = student.getSyd();
            xm.setText(xm_text);
            xy.setText(xy_text);
            zy.setText(zy_text);
//            if (isFirstIn) {
//                if (syd_text.contains("安徽")) {
//                    EventBus.getDefault().post(new MessageEvent("personal_center", 3, null));
//                }
//                nj = student.getRxnf();
//                njs = GetTimeUtil.stingToint(nj);
//                njs = GetTimeUtil.getYear() - njs;
//                int m = GetTimeUtil.getMonth();
//                if (m >= 9) ++njs;
//                if (njs == 4) {
//                    if (xb_text.equals("男")) {
//                        ToastUtil.showToast("欢迎" + xm_text + "学长！谁说毕业遥遥无期！");
//                    } else {
//                        ToastUtil.showToast("欢迎" + xm_text + "学姐！谁说毕业遥遥无期！");
//                    }
//                } else
//                    ToastUtil.showToast("欢迎来自" + njs + "年级的，" + xm_text + "同学!");
//            }

        }
        RequestOptions options = new RequestOptions();
        List<avatar> avatarList = MyApplication.getDaoInstant().getAvatarDao().loadAll();
        if (avatarList.size() > 0) {
            in = avatarList.get(0).getBytes();
            if (in != null && in.length > 0) {
                Glide.with(this).load(in)
                        .apply(options.circleCrop())
                        .into(iv_head);
            }
        }
        ImageView toolbar_avatar = findViewById(R.id.toolbar_avatar);

        if (in != null)
            Glide.with(this).load(in)
                    .apply(options.circleCrop())
                    .into(toolbar_avatar);
        else
            Glide.with(this).load(R.drawable.app_logo)
                    .apply(options.circleCrop())
                    .into(toolbar_avatar);
    }


    private void initViewPager() {
        viewpager = findViewById(R.id.view_pager);
        Adapter_Page adapter = new Adapter_Page(getSupportFragmentManager());
        adapter.addFragment(new Fragment_One(), "学业信息");
        adapter.addFragment(new Fragment_Two(), "个人信息");
        adapter.addFragment(new Fragment_Three(), "我的印记");
        viewpager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewpager);
        tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorPrimary));
        viewpager.setCurrentItem(1);
        tabLayout.post(() -> setIndicator(tabLayout, 30, 30));
    }

    private void initListener() {
        appbar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            iv_parallax.setTranslationY(verticalOffset);
            if (Math.abs(verticalOffset) == DensityUtil.dp2px(200) - toolbar.getHeight()) {
                if (iswhite) {
                    if (ImmersionBar.isSupportStatusBarDarkFont()) {
                        mImmersionBar.statusBarDarkFont(true).init();
                        isblack = true;
                        iswhite = false;
                    }
                }
                buttonBarLayout.setVisibility(View.VISIBLE);
                collapsing_toolbar.setContentScrimResource(R.color.white);
                iv_back.setBackgroundResource(R.drawable.back_black);
                iv_date.setBackgroundResource(R.drawable.login_out_black);

            } else {
                if (isblack) {
                    mImmersionBar.statusBarDarkFont(false).init();
                    isblack = false;
                    iswhite = true;
                }
                buttonBarLayout.setVisibility(View.INVISIBLE);
                collapsing_toolbar.setContentScrimResource(R.color.transparent);
                iv_back.setBackgroundResource(R.drawable.back_write);
                iv_date.setBackgroundResource(R.drawable.login_out_write);

            }
        });
    }


    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        assert tabStrip != null;
        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        assert llTab != null;
        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    /****************
     *
     * 发起添加群流程。群号：常熟理工安徽老乡群(340019004) 的 key 为： 1ACrGC4RFRuJrtKiCg7brAJsy06hzl9V
     * 调用 joinQQGroup(1ACrGC4RFRuJrtKiCg7brAJsy06hzl9V) 即可发起手Q客户端申请加群 常熟理工安徽老乡群(340019004)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("personal_center")) {
            switch (event.getWhat()) {
                case 3:
                    if (isFirstIn) {
                        AlertDialog alertDialog = new AlertDialog(personal_center.this);
                        alertDialog.builder();
                        alertDialog.setGone()
                                .setTitle("Hello")
                                .setMsg("发现来自安徽的童鞋一枚！\n欢迎加入安徽老乡群一起扎堆玩耍~\n常熟理工安徽老乡群：340019004")
                                .setPositiveButton("凑凑热闹", R.color.colorAccent, v -> joinQQGroup("1ACrGC4RFRuJrtKiCg7brAJsy06hzl9V"))
                                .show();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean("is_first_open_per", false);
                        editor.apply();
                    }
                    break;

            }
        }
    }


}
